import { Drawer, Loading } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import styles from './IFrameDrawer.module.scss';

export default function IFrameDrawer({ url, ...props }) {
  const frameRef = useRef();
  const [show, setShow] = useState(!!url);
  const [loading, setLoading] = useState(false);


  useEffect(() => {
    const handle = (e) => {
      if (e.data === 'closed') {
        setShow(false);
      }
    };
    window.addEventListener('message', handle);
    return () => window.removeEventListener('message', handle);
  }, []);

  useEffect(() => {
    setShow(!!url);
  }, [url]);

  useEffect(() => {
    if (show) {
      global.Cookie.set('token', global.TOKEN, { path: '/', maxAge: 10 });
      setLoading(true);
      const iframe = frameRef.current;
      
      if (iframe) iframe.src = url;
    }
  }, [show]);

  return (
    <Drawer
      visible={show}
      className={styles.iframeDrawer}
      closeMode={['esc', 'mask', 'close']}
      width="90%"
      {...props}
    >
      {loading && <Loading visible={loading} style={{ width: '100%', height: 300, position: 'absolute' }} />}
      <iframe ref={frameRef} id="orderView" width="100%" height="100%" style={{ border: 0, width: '100%', height: '100%' }} onLoad={() => setLoading(false)} />
    </Drawer>
  );
}
